package com.nmcc.app_adherence;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.TimeZone;
import java.util.UUID;

import android.os.Bundle;
import android.os.Environment;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Menu;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.view.View.OnClickListener;
import android.widget.Toast;
import java.util.Calendar;

import android.provider.Settings.Secure;

public class Persons extends Activity {

	//private static String CSV_PATH = "/data/data/com.nmcc.app_Adherence/lib/";
	private static String CSV_NAME = "Persons.csv";
	private static String BloodSlideNumA = "nill A";
	private static String BloodSlideNumB = "nill B";
    private Spinner spnRelations1, spnGender2, spnEnrolledCohot3, spnTreatmentsp, spnPersonToEditsp;
    private Button button;
	private static String house_number;
	private static String cluster_number;
	private static String house_guid;   
    private static String household_id;
    
    private static String hs;
    private static String cl;
    private static String hs_id;
	 private int newas1existingas2=1;
	 
	 private File root;
	 private ArrayList<File> fileList = new ArrayList<File>();
	 //private LinearLayout view;
	 
	//private static String cluster_number;
	//private static String house_number;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.persons_activity);
	
		initControls();
		
		//

		
		//String[] rRelations = getResources().getStringArray(R.array.relations_array);
		//String[] yYesNo = getResources().getStringArray(R.array.yesno_array);
		//String[] gGender = getResources().getStringArray(R.array.gender_array);
		addItemsOnSpinnerRelations();
		addItemsOnSpinnerGender();
		addItemsOnSpinnerEnrolledCohot();
		addItemsOnSpinnerTreatment();
		//addItemsOnSpinnerPersonToEdit();
		addListenerOnButton();
		getconstructPersonIDAndDEviceID();
		HideSomeControls();

		FillPersonsDetails();//be after the above controls so as to overwrite any auto generated id numbers, using stored values
		
		
        //age put validation
        EditText txtMonthBirth1 = (EditText) findViewById(R.id.txtMonthBirth);
        txtMonthBirth1.addTextChangedListener(new TextWatcher() {
        	public void afterTextChanged(Editable s) {
        		   try {
        		     int val = Integer.parseInt(s.toString());
        		     if(val > 12) {
        		        s.replace(0, s.length(), "12", 0, 2);
        		     } else if(val < 1) {
        		        s.replace(0, s.length(), "1", 0, 1);
        		     }
        		     
        		     int monthofbirth=val;
          		   final EditText txtyearbirth1=(EditText) findViewById(R.id.txtYearBirth); 
         	           int yearbirth= Integer.parseInt(txtyearbirth1.getText().toString());
         	            //reached birth day
  	      		 
          		   TextView myOutputBox = (TextView) findViewById(R.id.txtAge);
  	          	   myOutputBox.setText(String.valueOf(CalculateAge(monthofbirth,yearbirth)));
          		     
        		     
        		   } catch (NumberFormatException ex) {
        		      // Do something
        		   }
        		}
        	public void beforeTextChanged(CharSequence s, int start, 
     	           int count, int after) {
     	         }
     	         public void onTextChanged(CharSequence s, int start, 
     	           int before, int count) {
     	        	 //TextView mycluster = (TextView) findViewById(R.id.txtCluster_Number);
     	        	
     	         }
        });
		
        //year of birth put validation
        EditText txtYearBirth1 = (EditText) findViewById(R.id.txtYearBirth);
        txtYearBirth1.addTextChangedListener(new TextWatcher() {
        	public void afterTextChanged(Editable s) {
        		   try {
        			   
        			   Calendar c = Calendar.getInstance();
        			   int year = c.get(Calendar.YEAR);
        			  // int currentmonth = c.get(Calendar.MONTH);

        			   int val = Integer.parseInt(s.toString());
  	                         // int yearStr=year+1;
        		     if(val > year+1) {
        		        s.replace(0, s.length(), String.valueOf(year+1), 0, 4);
        		    	 
        		     } else if(val < 1900) {
        		       // s.replace(0, s.length(), "1900", 0, 4);
        		        if(val > 999) {
        		        	s.replace(0, s.length(), "1900", 0, 4);
        		        }
        		     }
        		     
 	          		    //calculate age
	           		 
	        		     //reached birth day
	        		    // age = (currentyear-yearofbirth)-1;
	        		   int yearofbirth=val;
	        		   final EditText txtmonthbirth1=(EditText) findViewById(R.id.txtMonthBirth); 
	       	           int monthbirth= Integer.parseInt(txtmonthbirth1.getText().toString());
	       	            //reached birth day
		      		 
	        		   TextView myOutputBox = (TextView) findViewById(R.id.txtAge);
       		 
	        		    myOutputBox.setText("");
	        		    
	          	 if(val > 1899) {//check if age is valid.1900
	          		if(val == year) {

		          	   myOutputBox.setText("0");
	        		     
	 		         }
	          		else{
	          			if(val < (year+1)) {

	 		          	   myOutputBox.setText(String.valueOf(CalculateAge(monthbirth,yearofbirth)));
	 	        		     
	 	 		         }
	          		}
 		         }
	          	 
	          	 
	          	 
        		   } catch (NumberFormatException ex) {
        		      // Do something
        		   }
        		}
        	public void beforeTextChanged(CharSequence s, int start, 
     	           int count, int after) {
     	         }
     	         public void onTextChanged(CharSequence s, int start, 
     	           int before, int count) {
     	        	 //TextView mycluster = (TextView) findViewById(R.id.txtCluster_Number);
     	        	
     	         }
        });		
		
        //age put validation
        EditText txtAge1 = (EditText) findViewById(R.id.txtAge);
        txtAge1.addTextChangedListener(new TextWatcher() {
        	public void afterTextChanged(Editable s) {
        		   try {
        		     int val = Integer.parseInt(s.toString());
        		     if(val > 122) {
        		        s.replace(0, s.length(), "122", 0, 2);
        		     } else if(val < 1) {
        		       // s.replace(0, s.length(), "0", 0, 1);
        		     }
        		   } catch (NumberFormatException ex) {
        		      // Do something
        		   }
        		}
        	public void beforeTextChanged(CharSequence s, int start, 
     	           int count, int after) {
     	         }
     	         public void onTextChanged(CharSequence s, int start, 
     	           int before, int count) {
     	        	 //TextView mycluster = (TextView) findViewById(R.id.txtCluster_Number);
     	        	
     	         }
        });
		
        
        
        //age put validation
        EditText txtDay1 = (EditText) findViewById(R.id.txtDayBirth);
        txtDay1.addTextChangedListener(new TextWatcher() {
        	public void afterTextChanged(Editable s) {
        		   try {
        		     int val = Integer.parseInt(s.toString());
        		     if(val > 31) {
        		        s.replace(0, s.length(), "31", 0, 2);
        		     } else if(val < 1) {
        		        s.replace(0, s.length(), "1", 0, 1);
        		     }
        		     //day 1 to 31
        		     
               		     
        		   } catch (NumberFormatException ex) {
        		      // Do something
        		   }
        		}
        	public void beforeTextChanged(CharSequence s, int start, 
     	           int count, int after) {
     	         }
     	         public void onTextChanged(CharSequence s, int start, 
     	           int before, int count) {
     	        	 //TextView mycluster = (TextView) findViewById(R.id.txtCluster_Number);
     	        	
     	         }
        });
        
	}

	
	public String getPhoneName(){
		BluetoothAdapter myDevice = BluetoothAdapter.getDefaultAdapter();
		String deviceName = myDevice.getName();
		return deviceName;
		
	}
	
	public String getPhoneMDAName(){
		String phon="nophonename";
		//File root = Environment.getExternalStorageDirectory();
		File root=new File(Environment.getExternalStorageDirectory() + "/opendatakit/username");
		
		getfile(root);
		
		if (root.exists()){
			 //Toast.makeText(getApplicationContext(), fileList.get(0).getName(), 5000).show();
				
			//for (int i=0; i< fileList.size(); i++){
				phon= fileList.get(0).getName();
				return phon;
			//}
		}
			
		
		return phon;
		
	}
	
	public ArrayList getfile(File dir) { 
		File listFile[] = dir.listFiles(); 
		if (listFile != null && listFile.length > 0) { 
			for (int i = 0; i < listFile.length; i++) { 
				if (listFile[i].isDirectory()) { 
					fileList.add(listFile[i]); 
					getfile(listFile[i]); 
					} else { 
						//if (listFile[i].getName().endsWith(".txt")) 
						//{ 
							fileList.add(listFile[i]);
						//} 
					} 
			}
		} return fileList;
	}
	
	private void getconstructPersonIDAndDEviceID(){
		MySQLiteHelper db = new MySQLiteHelper(this);
		
		  Calendar c = Calendar.getInstance();
	        
	        int hour = c.get(Calendar.HOUR);
			   int min = c.get(Calendar.MINUTE);
			   int second = c.get(Calendar.SECOND);
			   int milisecond = c.get(Calendar.MILLISECOND);
	 	   int day = c.get(Calendar.DAY_OF_MONTH);
				   int year = c.get(Calendar.YEAR);
				   int currentmonth = c.get(Calendar.MONTH);
				  //String AddInfoToPersonToday =currentmonth + day + hour + min + "-" + second;
				  String AddInfoToPersonToday =(year + currentmonth + day + hour + min + second + milisecond) + "-" + (milisecond);
				  
			//end here for the 
				   //folderLocationInSDCardBluetoothForToday ="/bluetooth/"+ day + "-" + currentmonth + "-" + year + "-GPS/";
			//end here for the 
				   
				  
				  
		//txtDeviceIDAndPersonID
		String deviceIdAndPersonID = Secure.getString(this.getContentResolver(),
                Secure.ANDROID_ID);
		
		String devname =getPhoneMDAName();//getPhoneName();//db.GetSettingDeviceName();//  //android.os.Build.MODEL;//
	//Toast.makeText(getApplicationContext(), "Using bluetooth name to construct the RDT label. Ensure that bluetooth is on. Bluetooth name: " + getPhoneName(), Toast.LENGTH_LONG).show();

		//String devname =deviceIdAndPersonID;
		//Toast.makeText(getApplicationContext(), devname, 5000).show();
		
		//if (devname.equals("null")){
			//Toast.makeText(getApplicationContext(), "Bluetooth is off. System will use device id instead of user friendly bluetooth name.", 5000).show();
			//devname=deviceIdAndPersonID;
		//}
		
        //Toast.makeText(this, deviceId, Toast.LENGTH_SHORT).show();
        EditText txtDeviceIDAndPersonID = (EditText) findViewById(R.id.txtDeviceIDAndPersonID);
        
        String SlideNum=devname + "-" + AddInfoToPersonToday;
        
        
        // give the variables
        BloodSlideNumA=SlideNum + " A";
        BloodSlideNumB=SlideNum + " B";
   
        txtDeviceIDAndPersonID.setText(BloodSlideNumA + "," + BloodSlideNumB);
	}
	
    private void initControls()
    {
        final EditText txtHouse_Number=(EditText) findViewById(R.id.txtHouse_Number);       
        final EditText txtCluster_Number=(EditText) findViewById(R.id.txtCluster_Number);       

        final EditText txtName=(EditText) findViewById(R.id.txtName);       
        final EditText txtPersonID=(EditText) findViewById(R.id.txtPersonID);       
        
        //final EditText txtRelationshiptoHHHead=(EditText) findViewById(R.id.txtRelationshiptoHHHead);       

        final EditText txthousehold_id=(EditText) findViewById(R.id.txthousehold_id);       
        final EditText txtMonthBirth=(EditText) findViewById(R.id.txtMonthBirth);       
        final EditText txtYearBirth=(EditText) findViewById(R.id.txtYearBirth); 
        final EditText txtAge=(EditText) findViewById(R.id.txtAge); 
        txtAge.setEnabled(false);
        //txtAge.setClickable(false);
        
		UUID uuid = UUID.randomUUID();
		txtPersonID.setText("uuid:" + uuid.toString());
		
		
		
		
        //final GlobalClass globalVariable = (GlobalClass) getApplicationContext();
        
        // Get name and email from global/application context
        //final String cluster_number  = globalVariable.getClusterNumber();
        //final String house_number = globalVariable.getHouseNumber();
       //txtCluster_Number.setText(globalVariable.getClusterNumber());
       //txtHouse_Number.setText(globalVariable.getHouseNumber());
		 MySQLiteHelper db = new MySQLiteHelper(this);
		//db.GetSetting(HouseNumAs1ClusterAs2HouseholdIDAs3;
		 hs = db.GetSetting(1);
		 cl = db.GetSetting(2);
		 hs_id = db.GetSetting(3);
	 		 
		 if(!hs.equals("")){
			 txtHouse_Number.setText(String.valueOf(hs));
         }	
	
		 if(!cl.equals("")){
			 txtCluster_Number.setText(cl);
         }	
		
		 if(!hs_id.equals("")){
			 txthousehold_id.setText(hs_id);
         }	
	
    }
	
    
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.persons, menu);
		return true;
	}

	 // add items into spinner dynamically
    public void addItemsOnSpinnerRelations() {
    	spnRelations1 = (Spinner) findViewById(R.id.spnRelations);
      List list = new ArrayList();
      list.add("Choose a relation" + "                                    " + "_00");
      list.add("HEAD" + "                                                 " + "_01");
      list.add("WIFE/HUSBAND" + "                                         " + "_02");
      list.add("SON OR DAUGHTER" + "                                      " + "_03");
      list.add("SON-IN-LAW OR DAUGHTER-IN-LAW" + "                        " + "_04");
      list.add("GRANDCHILD" + "                                           " + "_05");
      list.add("PARENT" + "                                               " + "_06");
      list.add("PARENT-IN-LAW" + "                                        " + "_07");      
      list.add("BROTHER OR SISTER" + "                                    " + "_08");
      list.add("OTHER RELATIVE" + "                                       " + "_09");
      list.add("ADOPTED/FOSTER/STEPCHILD" + "                             " + "_10");
      list.add("NOT RELATED" + "                                          " + "_11");      
      list.add("DON'T KNOW" + "                                           " + "_98");
      ArrayAdapter dataAdapter = new ArrayAdapter(this,android.R.layout.simple_spinner_item, list);
      dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
      spnRelations1.setAdapter(dataAdapter);
    }

    public void addItemsOnSpinnerGender() {
    	spnGender2 = (Spinner) findViewById(R.id.spnGender);
        List list = new ArrayList();
        list.add("Select Gender" + "                                      " + "_00");
        list.add("Male" + "                                               " + "_01");
        list.add("Female" + "                                             " + "_02");
 
        ArrayAdapter dataAdapter = new ArrayAdapter(this,android.R.layout.simple_spinner_item, list);
        dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spnGender2.setAdapter(dataAdapter);
      }
    
    public void addItemsOnSpinnerEnrolledCohot() {
    	spnEnrolledCohot3 = (Spinner) findViewById(R.id.spnEnrolledCohot);
        List list = new ArrayList();
        list.add("Choose an option" + "                                    " + "_00");
        list.add("Yes" + "                                                 " + "_01");
        list.add("No" + "                                                  " + "_02");

        ArrayAdapter dataAdapter = new ArrayAdapter(this,android.R.layout.simple_spinner_item, list);
        dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spnEnrolledCohot3.setAdapter(dataAdapter);
      }
    
    public void addItemsOnSpinnerTreatment() {
    	spnTreatmentsp = (Spinner) findViewById(R.id.spnTreatment);
        List list = new ArrayList();
        list.add("Choose an option" + "                                    " + "_00");
        list.add("CoArtem" + "                                                 " + "_01");
        list.add("SP" + "                                                  " + "_02");
        list.add("DHAp" + "                                                  " + "_03");
        list.add("Quinine" + "                                                  " + "_04");
        list.add("Referral" + "                                                  " + "_05");
        list.add("No treatment" + "                                                  " + "_06");
        
        ArrayAdapter dataAdapter = new ArrayAdapter(this,android.R.layout.simple_spinner_item, list);
        dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spnTreatmentsp.setAdapter(dataAdapter);
      }   
    
    private void FillPersonsDetails(){
    	MySQLiteHelper db4 = new MySQLiteHelper(this);
    	
    	String getSelectedPersonID = db4.GetSetting(4);//has ui8928uiw-gew787 for a new search

    	
				    	//String hs = db.GetSetting(1);//0 for a new serach
						//String cl = db.GetSetting(2);//0 for a new search
						
						if (getSelectedPersonID.equals("none"))//new house
			            {
							
							newas1existingas2=1;
				    		return;
			            }
						else {
							newas1existingas2=2;//existing house
						}


						       //fill the data
						final EditText txtHouse_Number=(EditText) findViewById(R.id.txtHouse_Number);  
				        final EditText txtCluster_Number=(EditText) findViewById(R.id.txtCluster_Number);       
				        final EditText txtName=(EditText) findViewById(R.id.txtName);  
				        final EditText txtPersonID=(EditText) findViewById(R.id.txtPersonID);       
				        final EditText txthousehold_id=(EditText) findViewById(R.id.txthousehold_id);       
			
				        spnRelations1 = (Spinner) findViewById(R.id.spnRelations);
				    	spnGender2 = (Spinner) findViewById(R.id.spnGender);
				    	spnEnrolledCohot3 = (Spinner) findViewById(R.id.spnEnrolledCohot);
				    	spnTreatmentsp = (Spinner) findViewById(R.id.spnTreatment);
				        final EditText txtMonthBirth=(EditText) findViewById(R.id.txtMonthBirth);  
				        final EditText txtYearBirth=(EditText) findViewById(R.id.txtYearBirth); 
				        final EditText txtAge=(EditText) findViewById(R.id.txtAge); 
				        final EditText txtDayBirth=(EditText) findViewById(R.id.txtDayBirth); 
				        final EditText txtDeviceIDAndPersonID=(EditText) findViewById(R.id.txtDeviceIDAndPersonID); 
				        

				   	    //givenPersonUniqueNumber
				   	 	MySQLiteHelper mh = new MySQLiteHelper(this);
					   	//MySQLiteHelper db1 = new MySQLiteHelper(this);
					   	
						SQLiteDatabase db = mh.getReadableDatabase();
						
						//String hs_id = db1.GetSetting(3);
			
						//Toast.makeText(getApplicationContext(), getSelectedPersonID, Toast.LENGTH_LONG).show();
					   	 

				 		String valueToReturn="0";
				 		String table = "Persons";
				         String[] columns = {"id","HouseNumber","ClusterNumber","HouseID","Name","RelationshipToHHHead","RelationshipToHHHeadLabel","household_id","EnrolledForCohot","Gender","DayBirth","MonthBirth","YearBirth","Age","Treatment","TreatmentLabel","PersonID","WasExported", "BloodSlideNumA", "BloodSlideNumB"};
				 	     String where = "id=" + getSelectedPersonID;//this is default so its acts as variable to be replaced
				 	         //String[] args = {"tagname", "tagname", "tagname", "tagname", "tagname"};
				 	         Cursor rs = db.query(table, columns, where, null, null, null, null);
				 	         if(rs.moveToFirst()){
				 	        	 String clustern = rs.getString(rs.getColumnIndex("ClusterNumber"));
				 	        	txtCluster_Number.setText(String.valueOf(clustern));
				 	        	 
				 	        	String HouseNumber = rs.getString(rs.getColumnIndex("HouseNumber"));
				 	        	txtHouse_Number.setText(String.valueOf(HouseNumber));
				 	        	 
				 	        	String PersonID = rs.getString(rs.getColumnIndex("PersonID"));
				 	        	txtPersonID.setText(String.valueOf(PersonID));
				 	        	 
				 	        	String household_id = rs.getString(rs.getColumnIndex("household_id"));
				 	        	txthousehold_id.setText(String.valueOf(household_id));
				 	        	 
				 	        	
				 	        	String name = rs.getString(rs.getColumnIndex("Name"));
				 	        	txtName.setText(String.valueOf(name));
				 	        	
				 	        	
				 	        	String DayBirth = rs.getString(rs.getColumnIndex("DayBirth"));
				 	        	txtDayBirth.setText(String.valueOf(DayBirth));
				 	        	
				 	        	String MonthBirth = rs.getString(rs.getColumnIndex("MonthBirth"));
				 	        	txtMonthBirth.setText(String.valueOf(MonthBirth));
				 	        	
				 	        	String YearBirth = rs.getString(rs.getColumnIndex("YearBirth"));
				 	        	txtYearBirth.setText(String.valueOf(YearBirth));
				 	        	
				 	        	String age = rs.getString(rs.getColumnIndex("Age"));
				 	        	txtAge.setText(String.valueOf(age));
				 	        	
				 	        	//spinners
				 	        	String relations = rs.getString(rs.getColumnIndex("RelationshipToHHHead"));
				 	        	int rel=getIndexRelations(relations);
				 	        	spnRelations1.setSelection(rel);//(db.GetHouseDetailsOfSelectedHouse(getSelectedHouseID, 10));
				 	           
				 	        	
				 	        	//String enrolledcoh = rs.getString(rs.getColumnIndex("EnrolledForCohot"));
				 	        	//Toast.makeText(getApplicationContext(), enrolledcoh, 10000).show();
				 	        	//int coh=getIndexCohort(enrolledcoh);
				 	        	//spnEnrolledCohot3.setSelection(coh);//(db.GetHouseDetailsOfSelectedHouse(getSelectedHouseID, 10));
				 	           
				 	          
				 	        	
				 	        	String gender = rs.getString(rs.getColumnIndex("Gender"));
				 	        	int gen=getIndexRelations(gender);
				 	        	spnGender2.setSelection(gen);//(db.GetHouseDetailsOfSelectedHouse(getSelectedHouseID, 10));

				 	        	String treatment = rs.getString(rs.getColumnIndex("Treatment"));
				 	        	int treat=getIndexRelations(treatment);
				 	        	spnTreatmentsp.setSelection(treat);//(db.GetHouseDetailsOfSelectedHouse(getSelectedHouseID, 10));
			 	        	
				 	        	//BloodSlideNumA
				 	        	BloodSlideNumA = rs.getString(rs.getColumnIndex("BloodSlideNumA"));
				 	        	BloodSlideNumB = rs.getString(rs.getColumnIndex("BloodSlideNumB"));

				 	        	txtDeviceIDAndPersonID.setText(BloodSlideNumA + "," + BloodSlideNumB);
				 	        	
				         	//if (id>0)
				                    // {
				 		        		//valueToReturn= "done";
			
				                     //} 
				                }  
				 	         
				 	         db.close(); 
			
					
			
						        
			  	//}          //}
	    	
	    }
	    
	      
    
    
    public void addListenerOnButton() {
    	//spnRelations1 = (Spinner) findViewById(R.id.spnRelations);
    	//spnGender2 = (Spinner) findViewById(R.id.spnGender);
    	//spnEnrolledCohot3 = (Spinner) findViewById(R.id.spnEnrolledCohot);
	   
	    //@Override
	  //  public void onClick(View v) {
	     // Toast.makeText(MainActivity.this,
	    //  "Result : " +
	             // "\nSpinner 1 : "+ String.valueOf(spnRelations1.getSelectedItem()) +
	             // "\nSpinner 2 : "+ String.valueOf(spnGender2.getSelectedItem()),
	             // "\nSpinner 2 : "+ String.valueOf(spnEnrolledCohot3.getSelectedItem()),
	        //  Toast.LENGTH_SHORT).show();
	  //  }
	}
    
   //   public void addPerson(int HouseNumber, int ClusterNumber,String HouseID, String Name, int RelationshipToHHHead, String household_id, int EnrolledForCohot, int Gender, int Age, String PersonID){
    private void HideSomeControls(){
        
    	    final TextView lblHouse_Number=(TextView) findViewById(R.id.lblHouse_Number); 
    	    final EditText txtHouse_Number=(EditText) findViewById(R.id.txtHouse_Number); 
	        final TextView lblCluster_Number=(TextView) findViewById(R.id.lblCluster_Number);
	        final EditText txtCluster_Number=(EditText) findViewById(R.id.txtCluster_Number);
	        final TextView lblPersonID=(TextView) findViewById(R.id.lblPersonID);
	        final EditText txtPersonID=(EditText) findViewById(R.id.txtPersonID);
	        final TextView lblhousehold_id=(TextView) findViewById(R.id.lblhousehold_id);       
	        final EditText txthousehold_id=(EditText) findViewById(R.id.txthousehold_id); 
	        final TextView lblDeviceIDAndPersonID=(TextView) findViewById(R.id.lblDeviceIDAndPersonID);
	        final EditText txtDeviceIDAndPersonID=(EditText) findViewById(R.id.txtDeviceIDAndPersonID);
	        
	      	final TextView lblTreatment=(TextView) findViewById(R.id.lblTreatment);
	      	final Spinner spnTreatmentsp = (Spinner) findViewById(R.id.spnTreatment);
	      
	      	final TextView lblEnrolledForCohot=(TextView) findViewById(R.id.lblEnrolledForCohot);
	      	final Spinner spnEnrolledCohot = (Spinner) findViewById(R.id.spnEnrolledCohot);
	      	
	        lblHouse_Number.setVisibility(View.GONE);
	        txtHouse_Number.setVisibility(View.GONE);
	        lblCluster_Number.setVisibility(View.GONE);
	        txtCluster_Number.setVisibility(View.GONE);
	        lblPersonID.setVisibility(View.GONE);
	        txtPersonID.setVisibility(View.GONE);
	        lblhousehold_id.setVisibility(View.GONE);
	        txthousehold_id.setVisibility(View.GONE);
	        //lblDeviceIDAndPersonID.setVisibility(View.GONE);
	        txtDeviceIDAndPersonID.setEnabled(false);
	        
	        lblTreatment.setVisibility(View.GONE);
	        spnTreatmentsp.setVisibility(View.GONE);
	        
	        lblEnrolledForCohot.setVisibility(View.GONE);
	        spnEnrolledCohot.setVisibility(View.GONE);
	       

	        
}
    
    public void EditSelectedPerson(View view)
    {
	   

    }
    
	public void SavePersonsDataLinker(View view)
    {
		
 	   //EntriesAllFilledIn
 	   if (!EntriesAllFilledIn()){
 		   //Toast.makeText(getApplicationContext(), "Empty BOX! Please complete all the entries before saving. If no GPS points available, enter, 0 in latitude and longitude.", Toast.LENGTH_LONG).show(); 
 		   Toast.makeText(getApplicationContext(), "Empty BOX! Please complete all the entries before saving.", 5000).show();
 		   return;
 	   }
 	   
 	   
 	   
		 final EditText txtHouse_Number=(EditText) findViewById(R.id.txtHouse_Number);       
	        final EditText txtCluster_Number=(EditText) findViewById(R.id.txtCluster_Number);       
	        final EditText txtName=(EditText) findViewById(R.id.txtName);  
	        final EditText txtPersonID=(EditText) findViewById(R.id.txtPersonID);       
	        final EditText txthousehold_id=(EditText) findViewById(R.id.txthousehold_id);       

	        spnRelations1 = (Spinner) findViewById(R.id.spnRelations);
	    	spnGender2 = (Spinner) findViewById(R.id.spnGender);
	    	//spnEnrolledCohot3 = (Spinner) findViewById(R.id.spnEnrolledCohot);
	    	spnTreatmentsp = (Spinner) findViewById(R.id.spnTreatment);
	        final EditText txtMonthBirth=(EditText) findViewById(R.id.txtMonthBirth);  
	        final EditText txtYearBirth=(EditText) findViewById(R.id.txtYearBirth); 
	        final EditText txtAge=(EditText) findViewById(R.id.txtAge); 
	        final EditText txtDayBirth=(EditText) findViewById(R.id.txtDayBirth); 
	        
	 	    //get _01 in say 'Head    _01'	 	   last3 = str.substring(str.length() - 3);
	   	    String rel =getLast3CharactersOfChoicesAsValue(String.valueOf(spnRelations1.getSelectedItem()));
	   	    String gend =getLast3CharactersOfChoicesAsValue(String.valueOf(spnGender2.getSelectedItem()));
	   	    String cohot = getLast3CharactersOfChoicesAsValue(String.valueOf(spnEnrolledCohot3.getSelectedItem()));
	   	    String treatment = getLast3CharactersOfChoicesAsValue(String.valueOf(spnTreatmentsp.getSelectedItem()));
   	   
	   	    
	   	    household_id=txthousehold_id.getText().toString();//need to find value
            //give values
        	house_number=txtHouse_Number.getText().toString();
        	cluster_number=txtCluster_Number.getText().toString();
        	
        	
        	int daybirth=0;
        	if(txtDayBirth.getText().toString().equals("")){
        		daybirth=0;
            }
        	else 
            {//txtDayBirth
        		daybirth=Integer.parseInt(txtDayBirth.getText().toString());
       	 	}
        	
        	if(newas1existingas2==1){
        		//change this
        		household_id=hs_id;
        	}
        	
        	
        	//int monthbirth=Integer.parseInt(txtMonthBirth.getText().toString());
        	//int yearbirth=Integer.parseInt(txtYearBirth.getText().toString());
        	
        	//if (IsChildBelow3Months(monthbirth, yearbirth)){
        		//Toast.makeText(getApplicationContext(), "Children below 3 months are excluded!", 5000).show();
        	 	   
        		//return;
        	//}
        	
        	
	   	    //database operations
            MySQLiteHelper db = new MySQLiteHelper(this);
            // add Books
            //db.DropAllTables();
            	
            //set the
         String datenow=db.getNow();
            	
            db.addPerson(newas1existingas2, Integer.parseInt(house_number),Integer.parseInt(cluster_number), hs_id, txtName.getText().toString(), rel,GetRelationshipLabel(rel), household_id, cohot, treatment,GetTreatmentLabel(treatment),gend, daybirth, Integer.parseInt(txtMonthBirth.getText().toString()),Integer.parseInt(txtYearBirth.getText().toString()),Integer.parseInt(txtAge.getText().toString()), txtPersonID.getText().toString(),datenow, BloodSlideNumA, BloodSlideNumB);   
            //db.addPerson(1, 2); 
	 	    
            
            
       	 //before clearing add the record to odk survey
       	 if (newas1existingas2==1){
       		 //ExportPersonsDataTakeToODKDirectNewMethod(view, newas1existingas2, household_id, txtPersonID.getText().toString());
       	 }
            
            // since member was successfully entered
            Toast.makeText(getApplicationContext(), "House member successfully added. You can add another member.", 10000).show();
            //clear boxes
            clearboxes();
            
           // addItemsOnSpinnerPersonToEdit();
            
            //Button txtName=(Button)findViewById(R.id.txtName);
           // txtName.requestFocus();
            //close this form
            final Context context = this;
            //give values
     	   Intent intent = new Intent(context, Persons.class);
            finish();
            
    }
	
	public void TransferToCSV(View view)
    {
	  // Dontsaverecord=false;
	// SaveIntoCSVLinker();
   generateCsvFile(view);
	//GetGPSLinker(view);
	  // Dontsaverecord=true;
	   
    }
	
		private void generateCsvFile(View view)
	    {
			//sFileName=CSV_NAME;
			
			final Context context = this;
			
	        final EditText txtHouse_Number=(EditText) findViewById(R.id.txtHouse_Number);       
	        final EditText txtCluster_Number=(EditText) findViewById(R.id.txtCluster_Number);       

	        final EditText txtName=(EditText) findViewById(R.id.txtName);  
	        
	        final EditText txtPersonID=(EditText) findViewById(R.id.txtPersonID);       
	        
	        //final EditText txtRelationshiptoHHHead=(EditText) findViewById(R.id.txtRelationshiptoHHHead);       

	        //final EditText txtGender=(EditText) findViewById(R.id.txtGender); 
	    	
	        spnRelations1 = (Spinner) findViewById(R.id.spnRelations);
	    	spnGender2 = (Spinner) findViewById(R.id.spnGender);
	    	spnEnrolledCohot3 = (Spinner) findViewById(R.id.spnEnrolledCohot);
	        
	         
	        final EditText txtMonthBirth=(EditText) findViewById(R.id.txtMonthBirth);
	        final EditText txtYearBirth=(EditText) findViewById(R.id.txtYearBirth);
	        final EditText txtAge=(EditText) findViewById(R.id.txtAge); 
	        
	 	try
	 	{
	
	 		
			String outputFile =Environment.getExternalStorageDirectory() + CSV_NAME;
			
			// before we open the file check to see if it already exists
			boolean alreadyExists = new File(outputFile).exists();
	
	 	    //FileWriter writer = new FileWriter(sFileName);
	 		File root = Environment.getExternalStorageDirectory();
	 		File gpxfile = new File(root, CSV_NAME);
	 		FileWriter writer = new FileWriter(gpxfile, true);
	 		         		
	 		//count lines if already has data
	
			// if the file didn't already exist then we need to write out the header line
			if (!alreadyExists)
			{
	    	    writer.append("House_Number");
	     	    writer.append(',');
	     	    writer.append("ClusterNumber");
	     	    writer.append(',');
	     	    writer.append("Name");
	    	    writer.append(',');             	    
		     	writer.append("PersonID");
	     	    writer.append(',');
	     	    writer.append("RelationshipToHHHEad");
	     	    writer.append(',');
	     	    writer.append("EnrolledForCohot");
	     	    writer.append(',');	     	    
	     	    writer.append("Gender");
	     	    writer.append(',');
	     	    writer.append("MonthBirth");
	     	    writer.append(',');
	     	    writer.append("YearBirth");
	     	    writer.append(',');
	     	    writer.append("Age");
	     	    writer.append('\n');  
	
			}		
	
	 		//now add the data, same order as above, check corresponding fields
        	
	 	    writer.append(txtHouse_Number.getText().toString());
	 	    writer.append(',');
	 	    writer.append(txtCluster_Number.getText().toString());
	 	    writer.append(',');
	 	    writer.append(txtName.getText().toString());
	 	    writer.append(',');
	 	    
	 	    writer.append(txtPersonID.getText().toString());
	 
	 	    writer.append(",");
	 	    //get _01 in say 'Head    _01'	 	   last3 = str.substring(str.length() - 3);
	   	    writer.append(getLast3CharactersOfChoicesAsValue(String.valueOf(spnRelations1.getSelectedItem())));
	 	    writer.append(",");
	 	    writer.append(getLast3CharactersOfChoicesAsValue(String.valueOf(spnEnrolledCohot3.getSelectedItem())));
	 	    writer.append(',');	
	 	    writer.append(getLast3CharactersOfChoicesAsValue(String.valueOf(spnGender2.getSelectedItem())));

	 	    writer.append(',');
	 	    writer.append(txtMonthBirth.getText().toString());
	 	    writer.append(',');
	 	    writer.append(txtYearBirth.getText().toString());
	 	    writer.append(',');
	 	    writer.append(txtAge.getText().toString());
	 	    writer.append('\n');
	 	    //generate whatever data you want
	  
	 	    writer.flush();
	 	    writer.close();
	 	    
	 	}
	 	catch(IOException e)
	 	{
	 	     e.printStackTrace();
	 	} 
	   }
	
		 private String getLast3CharactersOfChoicesAsValue(String gnstr) {
			 //get _01 in say 'Head    _01'	 	   last3 = str.substring(str.length() - 3);
	 	       //String relat=String.valueOf(spnRelations1.getSelectedItem());
	 	       //check if its first option 'Select Gender.....  _00', then return null
	 	      
			 String lastcharacterUseForCompare = "0";
			 String Extractedlastcharacter = gnstr.substring(gnstr.length() - 1);
			 
			 if (lastcharacterUseForCompare==Extractedlastcharacter){
	 	    	   return null;
	 	      } else {
	 	    		   return gnstr.substring(gnstr.length() - 3);
	 	    		  
	 	       }
	 	    	   
		 }
		 
		 public boolean EntriesAllFilledIn(){
      	   //boolean YesCompleted;
		        
			final EditText txtHouse_Number=(EditText) findViewById(R.id.txtHouse_Number);       
				   		        
			 final EditText txtCluster_Number=(EditText) findViewById(R.id.txtCluster_Number);       
		        final EditText txtName=(EditText) findViewById(R.id.txtName);  
		        final EditText txtPersonID=(EditText) findViewById(R.id.txtPersonID);       
		        final EditText txthousehold_id=(EditText) findViewById(R.id.txthousehold_id);       

		        spnRelations1 = (Spinner) findViewById(R.id.spnRelations);
		    	spnGender2 = (Spinner) findViewById(R.id.spnGender);
		    	spnEnrolledCohot3 = (Spinner) findViewById(R.id.spnEnrolledCohot);
		    	spnTreatmentsp = (Spinner) findViewById(R.id.spnTreatment);
		    	
		        final EditText txtMonthBirth=(EditText) findViewById(R.id.txtMonthBirth);  
		        final EditText txtYearBirth=(EditText) findViewById(R.id.txtYearBirth); 
		        final EditText txtAge=(EditText) findViewById(R.id.txtAge); 
		        
		 	    //get _01 in say 'Head    _01'	 	   last3 = str.substring(str.length() - 3);
		   	    String rel =getLast3CharactersOfChoicesAsValue(String.valueOf(spnRelations1.getSelectedItem()));
		   	    String gend =getLast3CharactersOfChoicesAsValue(String.valueOf(spnGender2.getSelectedItem()));
		   	    String cohot = getLast3CharactersOfChoicesAsValue(String.valueOf(spnEnrolledCohot3.getSelectedItem()));
	     	   
		   	   String treat = getLast3CharactersOfChoicesAsValue(String.valueOf(spnTreatmentsp.getSelectedItem()));
	     	   
		   	  if(txtHouse_Number.getText().toString().equals("")){
	                 return false;
	             }		   	    
		   	    
             if(txtCluster_Number.getText().toString().equals("")){
                 return false;
             }
             
             if(txtName.getText().toString().equals("")){
                 return false;
             }
             
             if(txtPersonID.getText().toString().equals("")){
                 return false;
             }
             
             if(txthousehold_id.getText().toString().equals("")){
                 return false;
             }
             
             if(rel.equals("_00")){
                 return false;
             }
             
             if(gend.equals("_00")){
                 return false;
             }
             
             //if(cohot.equals("_00")){
               //  return false;
             //}
             
             //if (treat.equals("_00")){
            	// return false;
            // }
             
             //if(txtMonthBirth.getText().toString().equals("")){
               //  return false;
            // }
             //if(txtYearBirth.getText().toString().equals("")){
               //  return false;
             //}
             if(txtMonthBirth.getText().toString().equals("")){
                 return false;
             }
             if(txtYearBirth.getText().toString().equals("")){
                 return false;
             }
             if(txtAge.getText().toString().equals("")){
                 return false;
             }
             //else return true
             return true;
         }
		 
		 public void clearboxes(){
		        final EditText txtCluster_Number=(EditText) findViewById(R.id.txtCluster_Number);       
		        final EditText txtHouse_Number=(EditText) findViewById(R.id.txtHouse_Number);       
		        		        
		        final EditText txtName=(EditText) findViewById(R.id.txtName);  
		        final EditText txtPersonID=(EditText) findViewById(R.id.txtPersonID);       
		        final EditText txthousehold_id=(EditText) findViewById(R.id.txthousehold_id);       

		        spnRelations1 = (Spinner) findViewById(R.id.spnRelations);
		    	spnGender2 = (Spinner) findViewById(R.id.spnGender);
		    	spnEnrolledCohot3 = (Spinner) findViewById(R.id.spnEnrolledCohot);
		    	spnTreatmentsp = (Spinner) findViewById(R.id.spnTreatment);
		          
		        final EditText txtMonthBirth=(EditText) findViewById(R.id.txtMonthBirth);  
		        final EditText txtYearBirth=(EditText) findViewById(R.id.txtYearBirth); 
		        final EditText txtAge=(EditText) findViewById(R.id.txtAge);
		 	    //get _01 in say 'Head    _01'	 	   last3 = str.substring(str.length() - 3);
		   	    String rel =getLast3CharactersOfChoicesAsValue(String.valueOf(spnRelations1.getSelectedItem()));
		   	    String gend =getLast3CharactersOfChoicesAsValue(String.valueOf(spnGender2.getSelectedItem()));
		   	    String cohot = getLast3CharactersOfChoicesAsValue(String.valueOf(spnEnrolledCohot3.getSelectedItem()));
	     	   
		   	// txtHouse_Number.setText("");    
		   	// txtCluster_Number.setText("");
		   	//txthousehold_id.setText("");     
		   	txtName.setText("");
		   	
		    UUID uuid = UUID.randomUUID();
		   	txtPersonID.setText("uuid:" + uuid.toString());
     
		   	txtMonthBirth.setText("");   
		   	txtYearBirth.setText("");  
		   	txtAge.setText("");  
		   	//need fresh reload
		   	addItemsOnSpinnerRelations();
		   	addItemsOnSpinnerGender();
		   	addItemsOnSpinnerEnrolledCohot();
		   	addItemsOnSpinnerTreatment();
		   	
		 }
		  
		 
		    public String GetTreatmentLabel(String treatmentValue){
		       	 String valueToReturn;
		       	 //txtName.getText().toString().equals("")
		       	         if (treatmentValue.equals("_00"))
		       	         	{
		       	        	 	valueToReturn= "Blank entry";
		       	         	}
		       	 
		       	         else if (treatmentValue.equals("_01"))
				            {
				        	 valueToReturn= "CoArtem";

				        	 }
				         else if (treatmentValue.equals("_02"))
				        	 {
				        	 valueToReturn= "SP";
				        	 } 
				         else if (treatmentValue.equals("_03"))
				             {
				        	 valueToReturn= "DHAp";
				        	 } 
				         else if (treatmentValue.equals("_04")) 
			                 {
			        	     valueToReturn= "Quinine";
			        	     } 
				         else if (treatmentValue.equals("_05"))
			                 {
			        	     valueToReturn= "Referral";
			        	     }
				         else if (treatmentValue.equals("_06"))
		                    {
		       	            valueToReturn= "No treatment";
		       	            } 
				         else 
				             {
				        	 throw new IllegalArgumentException();
				        	 }
			         return valueToReturn;

			         //return null;
			 }
		 
		    public String GetRelationshipLabel(String relationValue){
		       	 String valueToReturn;
		       	 //txtName.getText().toString().equals("")
				         if (relationValue.equals("_01"))
				            {
				        	 valueToReturn= "HEAD";

				        	 }
				         else if (relationValue.equals("_02"))
				        	 {
				        	 valueToReturn= "WIFE/HUSBAND";
				        	 } 
				         else if (relationValue.equals("_03"))
				             {
				        	 valueToReturn= "SON OR DAUGHTER";
				        	 } 
				         else if (relationValue.equals("_04")) 
			                 {
			        	     valueToReturn= "SON-IN-LAW OR DAUGHTER-IN-LAW";
			        	     } 
				         else if (relationValue.equals("_05"))
			                 {
			        	     valueToReturn= "GRANDCHILD";
			        	     }
				         else if (relationValue.equals("_06"))
		                    {
		       	            valueToReturn= "PARENT";
		       	            } 
				         else if (relationValue.equals("_07"))
		                    {
		       	            valueToReturn= "PARENT-IN-LAW";
		       	            } 
				         else if (relationValue.equals("_08"))
		                    {
		       	            valueToReturn= "BROTHER OR SISTER";
		       	            } 
				         else if (relationValue.equals("_09"))
		                    {
		       	            valueToReturn= "OTHER RELATIVE";
		       	            } 
				         else if (relationValue.equals("_10"))
		                    {
		       	            valueToReturn= "ADOPTED/FOSTER/STEPCHILD";
		       	            } 
				         else if (relationValue.equals("_11"))
		                    {
		       	            valueToReturn= "NOT RELATED";
		       	            } 
				         else if (relationValue.equals("_98"))
		                    {
		       	            valueToReturn= "DON'T KNOW";
		       	            } 
				         				         
				         else 
				             {
				        	// valueToReturn=" ";
				        	 throw new IllegalArgumentException();
				        	 }
			         return valueToReturn;

			         //return null;
			 }
		    
		    
		    public int CalculateAge(int monthofbirth, int yearofbirth){
		    	try {
     			   
     			   Calendar c = Calendar.getInstance();
     			   int year = c.get(Calendar.YEAR);
     			   int currentmonth = c.get(Calendar.MONTH);

       		     //calculate age
     		 
     		     //reached birth day
     		    // age = (currentyear-yearofbirth)-1;
     		     int age=0;
     		   //final EditText txtmonthbirth1=(EditText) findViewById(R.id.txtMonthBirth); 
    	          // int monthbirth= Integer.parseInt(txtmonthbirth1.getText().toString());
    	            //reached birth day
 
      		     if(monthofbirth <= currentmonth) {
	      		    	age = year-yearofbirth;
	       		     } else if(monthofbirth > currentmonth) {
	       		    	 //not reached birth day
	       		    	age = (year-yearofbirth)-1;
	       		     }		    	

	        		   return age;
	        		   
     		   //TextView myOutputBox = (TextView) findViewById(R.id.txtAge);
	          	   //myOutputBox.setText(String.valueOf(age));
     		     
     		     
     		   } catch (NumberFormatException ex) {
     			  return 0;
     		      // Do something
     		   }
		    }
		    
		    
		    public boolean IsChildBelow3Months(int monthofbirth, int yearofbirth){
		    	try {
     			   
     			   Calendar c = Calendar.getInstance();
     			   int year = c.get(Calendar.YEAR);
     			   int currentmonth = c.get(Calendar.MONTH);

       		     //calculate age
     		 
     		     //reached birth day
     		    // age = (currentyear-yearofbirth)-1;
     		     int age=0;
     		   //final EditText txtmonthbirth1=(EditText) findViewById(R.id.txtMonthBirth); 
    	          // int monthbirth= Integer.parseInt(txtmonthbirth1.getText().toString());
    	            //reached birth day
	      		     
     		    //if(monthofbirth <= currentmonth) {  
     		         if(monthofbirth <= currentmonth) {
	      		    	age = year-yearofbirth;
	       		     } else if(monthofbirth > currentmonth) {
	       		    	 //not reached birth day
	       		    	age = (year-yearofbirth)-1;
	       		     }
	      		     
     		         boolean isbelow3months=false;
	      		     //now we know age
     		        if(age <= 1) {//its 0 years
     		        	//its a baby
     		        	int months=currentmonth-monthofbirth;
     		        	if(months < 3) {
     		        		isbelow3months=true;
     		        		
     		        	}
     		        }
     		         
     		         
	        		   return isbelow3months;
	        		   
     		   //TextView myOutputBox = (TextView) findViewById(R.id.txtAge);
	          	   //myOutputBox.setText(String.valueOf(age));
     		     
     		     
     		   } catch (NumberFormatException ex) {
     			  return false;
     		      // Do something
     		   }
		    }
		    
		    
		    private int getIndexRelations(String textvalue){
		    	if (textvalue.equals("_00"))
	            {
		    		return 0;
	            }

		    	else if (textvalue.equals("_01"))
	            {
		    		return 1;
	            }
		    	else if (textvalue.equals("_02"))
	            {
		    		return 2;
	            }
		    	else if (textvalue.equals("_03"))
	            {
		    		return 3;
	            }	    
		    	
		    	else if (textvalue.equals("_04"))
	            {
		    		return 4;
	            }

		    	else if (textvalue.equals("_05"))
	            {
		    		return 5;
	            }
		    	else if (textvalue.equals("_06"))
	            {
		    		return 6;
	            }
		    	else if (textvalue.equals("_07"))
	            {
		    		return 7;
	            }
		    	else if (textvalue.equals("_08"))
	            {
		    		return 8;
	            }

		    	else if (textvalue.equals("_09"))
	            {
		    		return 9;
	            }
		    	else if (textvalue.equals("_10"))
	            {
		    		return 10;
	            }
		    	else if (textvalue.equals("_11"))
	            {
		    		return 11;
	            }	
		    	else if (textvalue.equals("_98"))
	            {
		    		return 12;
	            }		    	
		    	else
	            {
		    		return 0;
	            }
		    	
		   }

		    private int getIndexGender(String textvalue){
		    	if (textvalue.equals("_00"))
	            {
		    		return 0;
	            }

		    	else if (textvalue.equals("_01"))
	            {
		    		return 1;
	            }
		    	else if (textvalue.equals("_02"))
	            {
		    		return 2;
	            }
		    	
		    	else
	            {
		    		return 0;
	            }
		    	
		   }

		    
		    private int getIndexCohort(String textvalue){
		    	if (textvalue.equals("_00"))
	            {
		    		return 0;
	            }

		    	else if (textvalue.equals("_01"))
	            {
		    		return 1;
	            }
		    	else if (textvalue.equals("_02"))
	            {
		    		return 2;
	            }
		    	else
	            {
		    		return 0;
	            }
		    	
		   }
		    
		    private int getIndexTreatment(String textvalue){
		    	if (textvalue.equals("_00"))
	            {
		    		return 0;
	            }

		    	else if (textvalue.equals("_01"))
	            {
		    		return 1;
	            }
		    	else if (textvalue.equals("_02"))
	            {
		    		return 2;
	            }
		    	else if (textvalue.equals("_03"))
	            {
		    		return 3;
	            }	    
		    	
		    	else if (textvalue.equals("_04"))
	            {
		    		return 4;
	            }

		    	else if (textvalue.equals("_05"))
	            {
		    		return 5;
	            }
		    	else if (textvalue.equals("_06"))
	            {
		    		return 6;
	            }
		    	
		    	else
	            {
		    		return 0;
	            }
		    	
		   }
		    
		    

	  		 public void ExportPersonsDataTakeToODKDirectNewMethod(View view, int newAs1ExistingAs2, String newhouseguid, String person_idx ){
	  			 SQLiteDatabase db;
	  			 
	  			String dir = Environment.getExternalStorageDirectory().getPath();
	  			File dbfile = new File(dir+"/opendatakit/survey/metadata/webDb/http_localhost_8635/0000000000000001.db"); 
	  			db = SQLiteDatabase.openOrCreateDatabase(dbfile, null);
	  			
	  				//UUID uuid = UUID.randomUUID();
	  				//String newhouseguid=uuid.toString();

	  				if (newAs1ExistingAs2==2){
	  			        	 // db.execSQL("UPDATE GPSData SET " +
	  			      		//"HouseNumber=" + HouseNumber + 
	  			      		//"', comment='" + comment + "' WHERE HouseID='" + HouseID + "'");

	  		               }
	  			          else if (newAs1ExistingAs2==1){
	  	                      //2014-10-06-10.57.45.666000000
	  			        	  //2014-10-05T22:53:34.293000000
	  			        	  
	  			        	  //2014-10-06T11:08:19.894000000
	  			        	  //2014-10-06T11:18:21.942000000
	  			        	Timestamp timestamp = new Timestamp(System.currentTimeMillis());
	  			          SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.");
	  			          //yyyy-MM-dd'T'HH:mm:ssZ
	  			          
	  			          format.setTimeZone(TimeZone.getDefault()); // Set the TimeZone to whatever you are expecting.
	  			          String timestampedDate = format.format(timestamp) + String.format("%09d", timestamp.getNanos());
  			          
	  			        	  
	  			        	  
	  			        	  ContentValues cv = new ContentValues();
	  			        	  cv.put("_id", "uuid:"+ person_idx);
	  			        	  cv.put("_sync_state", "new_row"); 
	  			        	  cv.put("_form_id", "member"); 
	  			        	  cv.put("_locale", "default"); 
	  			        	  cv.put("_savepoint_timestamp", timestampedDate); //redo time need .89000000000
	  			        	  cv.put("_savepoint_creator", "anonymous"); 
	  			        	 
	  			        	  //housedetails
	  			        	  //cv.put("place_name_selected", placename); 
	  			        	  cv.put("household_id", newhouseguid); 
	  			        	  //cv.put("comment", comment); 
	  			        	  //cv.put("household_id_selected", newhouseguid);
	  			        	 // cv.put("comment_selected", comment);
	  			        	  cv.put("person_id", person_idx);
	  			        	  cv.put("person_id_selected", person_idx);
	  			        	  
	  			        	  db.insert("household_member", null, cv);
	  			        	  //db.close();
	  			          }

	  			          db.close(); 
	  		
	  		} 
		    
		    
}
